//签名插件类

define(function (require, exports, module) {
	require("../../PDFData/Signature.js");
	require("../../PDFData/SignatureDoc.js");
	var SignatureMousePtHandler = require("./SignatureMousePtHandler.js");
	var SignatureToolHandler = require("./SignatureToolHandler.js");
	WebPDF.SignaturePluginName = "Signature Plugin";
	
    /**
     * Plugin of Sinature
     * @param {WebPDF.ReaderApp} readerApp app instance
     * @extends {WebPDF.IReaderPlugin}
     * @constructor
     */
    WebPDF.SignaturePlugin = function (readerApp) {
        var _readerApp = readerApp,
            _self = this,
            _signatureTool = null,
            _signatureList = {},
            _signatureAddListId = {},
            _signatureDeletedListId = {},
            _signatureDocList = {},
            _curSignatureId = null;
        	_signatureListMax = 0,
        	_curSignatureNum = 0,
        	_signcodeUrl = "",
        	_signToPageCompleteEventHandler = null;
        
        function GetCurrentStrWidth(text, font) {
        	var offset = 10;
            var currentObj = $('<pre>').hide().appendTo(document.body);
            $(currentObj).html(text).css('font', font);
            var width = currentObj.width();
            currentObj.remove();
            return (width + offset);//末尾预留点空间
        }
        //获取Plugin名称;
        this.getPluginName = function () {
            return WebPDF.SignaturePluginName;
        };
        //插件被注册的时候调用;
        this.onRegister = function () {
        };
        
        this.hideEditSign = function(htmlObjcet,backgroundBoolean){
        	if(backgroundBoolean){
        		var htmlObjectId = htmlObjcet.attr("id");
        		jQuery("#"+htmlObjectId+"_fg").hide();
        	}
        	htmlObjcet.css("border","1px solid transparent");
        	htmlObjcet.find(".fwr-sign-dragImg").hide();
        	htmlObjcet.find(".fwr-sign-delImg").hide();
        	htmlObjcet.css('z-index',50);
        	htmlObjcet.find(".fwr-sign-scaleImg").hide();
        };
        
        this.showEditSign = function(htmlObjcet,backgroundBoolean){
        	if(backgroundBoolean){
        		var htmlObjectId = htmlObjcet.attr("id");
        		jQuery("#"+htmlObjectId+"_fg").show();
        	}
        	htmlObjcet.css("border","1px solid #f78f20");
        	htmlObjcet.find(".fwr-sign-dragImg").show();
        	htmlObjcet.find(".fwr-sign-delImg").show();
        	htmlObjcet.find(".fwr-sign-scaleImg").show();
        };
        
        this.moveHtmlObject = function(htmlObject,offsetX,offsetY,pageView){
        	var docView = _readerApp.getDocView();
        	var scale = docView.getScale();
        	var pageViewWidth = pageView.getPageViewWidth();
        	var pageViewHeight = pageView.getPageViewHeight();
        	var maxLeft = pageViewWidth-htmlObject.width()-23;
			var maxTop = pageViewHeight-htmlObject.height()-12;
			var signatureId = _self.getSignatureDocObjIdFromObj(htmlObject);
			var signatureDocObj = _self.getSingnatureFromPage(signatureId, pageView);
			var left = parseInt(htmlObject.css("left")) + offsetX;
			var top = parseInt(htmlObject.css("top")) + offsetY;
			if(left < 2){
				left = 2;
			}else if(left > maxLeft){
				left = maxLeft;
			}
			if(top < 12){
				top = 12;
			}else if(top > maxTop){
				top = maxTop;
			}
			htmlObject.css({"left": left + "px", "top": top + "px"});
			signatureDocObj.setPosX(parseInt(left / scale + 0.5));
			signatureDocObj.setPosY(parseInt(top / scale + 0.5));
        };
        
        /**
         * type: nw	此光标指示矩形框的边缘可被向上及向左移动（北/西）。
         * 		 se	此光标指示矩形框的边缘可被向下及向右移动（南/东）。
         * 		 sw	此光标指示矩形框的边缘可被向下及向左移动（南/西）。
         * @param htmlObject
         * @param offsetX
         * @param offsetY
         * @param type
         */
        this.changeHtmlObjct = function(htmlObject,offsetX,offsetY,direction){
        	var docView = _readerApp.getDocView();
        	var scale = docView.getScale();
        	var idStrArray = htmlObject.attr("id").split("_");
        	var pageView = docView.getPageView(parseInt(idStrArray[idStrArray.length - 3]));
        	var pageViewWidth = pageView.getPageViewWidth();
        	var pageViewHeight = pageView.getPageViewHeight();
        	var curLeft = parseFloat(htmlObject.css("left"));
        	var curTop = parseFloat(htmlObject.css("top"));
        	var curWidth = htmlObject.width();
        	var curHeight = htmlObject.height();
        	
        	var maxWidth = pageViewWidth - curLeft - 23;
			var maxHeight = pageViewHeight - curTop - 12;
        	if(direction=="sw" || direction == "nw"){
        		maxWidth = curLeft + curWidth -3.5;
        		if(offsetX > 0){
        			offsetX = parseInt("-"+offsetX);
        		}else{
        			offsetX = Math.abs(offsetX);
        		}
        	}
        	if(direction == "nw"){
        		maxHeight = curTop + curHeight -12;
        		if(offsetY > 0){
        			offsetY =  parseInt("-"+offsetY);
        		}else{
        			offsetY = Math.abs(offsetY);
        		}
        	}
			var signatureId = _self.getSignatureDocObjIdFromObj(htmlObject);
			var signatureDocObj = _self.getSingnatureFromPage(signatureId, pageView);
        	var width = curWidth + offsetX;
        	var height = curHeight + offsetY;
			if (signatureDocObj.getType() == WebPDF.PDFData.SignatureType.Text) {
				var minWidth = 100 * scale;
				var minHeight = 26 * scale;
				width = Math.max(width, minWidth);
				width = Math.min(width, maxWidth);
				height = Math.max(height, minHeight);
				height = Math.min(height, maxHeight);
			} else {
				var minWidth = 16 * scale;
				var minHeight = 16 * scale;
				width = Math.max(width, minWidth);
				width = Math.min(width, maxWidth);
				height = Math.max(height, minHeight);
				height = Math.min(height, maxHeight);
				
				var orgImgWidth = signatureDocObj.getOriginalImgWidth(),
					orgImgHeight = signatureDocObj.getOriginalImgHeight();
				var xscale = width / orgImgWidth;
				var yscale = height / orgImgHeight;
				if (xscale < yscale) {
					height = xscale * orgImgHeight;
				} else {
					width = yscale * orgImgWidth;
				}
				
				if (width < minWidth) {
					width = minWidth;
					height = width * orgImgHeight / orgImgWidth;
					height = Math.min(height, maxHeight);
				}
				if (height < minHeight) {
					height = minHeight;
					width = height * orgImgWidth / orgImgHeight;
					width = Math.min(width, maxWidth);
				}
			}
			
			htmlObject.css({"width": parseInt(width+0.5) + "px", "height": parseInt(height+0.5) + "px"});
			if(direction == "nw" || direction == "sw"){
				htmlObject.css("left",curWidth-parseInt(width+0.5)+curLeft);
			}
			if(direction == "nw"){
				htmlObject.css("top",curHeight-parseInt(height+0.5)+curTop);
			}
			
			signatureDocObj.setWidth(parseInt(width / scale + 0.5));
			signatureDocObj.setHeight(parseInt(height / scale + 0.5));
        };
        
        this.bindInputEvent = function(inputId) {
        	_signatureTool && _signatureTool.bindInputEvent(inputId);
        };
        
        function _getSignatureList(callback) {
        	$.ajax({
                url: _readerApp.getOptions().url + "signatureList",
                dataType: 'json',
                type: 'GET',
                cache: false,
                success: function (response) {
                    try {
                        if(response.success){
                        	_signatureListMax = response.limit;
                        	/*_signcodeUrl = response.signcodeUrl;
                        	var arrObj = window.top.location.href.split("//");
                        	_signcodeUrl += arrObj[0] + "//";
                        	var end = arrObj[1].indexOf("/");
                        	_signcodeUrl += arrObj[1].substring(0, end);*/
                            _signcodeUrl = "/api/sigcode";
                        	callback(response.data);
                        }else{
                        	WebPDF.alert(_readerApp, null, "Get signature list failed.");
                        	console.error('Get signature list failed,' + response.toString());
                        }
                    }catch (ex) {
                        console.error(ex);
                    }
                },
                error: function () {
                	console.error('Get signature list failed,');
                }
            });
        };
        
        function _bindEvents(){
            $(_readerApp).on(WebPDF.EventList.DOCVIEW_PRE_RESIZE, function(){
            	var docView = _readerApp.getDocView();
            	var scale = docView.getScale();
            	for (var key in _signatureDocList) {
            		var pageSignatureObj = _signatureDocList[key];
            		if (pageSignatureObj) {
            			var pageView = docView.getPageView(pageSignatureObj.index);
            			var signatureContainerId = _self.getSignatureContainerId(pageView);
            			var pageViewWidth = pageView.getPageViewWidth();
            			var pageViewHeight = pageView.getPageViewHeight();
            			for (var id in pageSignatureObj.signatures) {
            				var signatureDocObj = pageSignatureObj.signatures[id];
            				if (signatureDocObj) {
								var w = parseInt(signatureDocObj.getWidth() * scale + 0.5);
								var h = parseInt(signatureDocObj.getHeight() * scale + 0.5);
								var x = parseInt(signatureDocObj.getPosX() * scale + 0.5);
								var y = parseInt(signatureDocObj.getPosY() * scale + 0.5);
								var maxX = pageViewWidth-w-23;
								var maxY = pageViewHeight-h-12;
								if(x < 2){
									x = 2;
								} else if(x > maxX){
									x = maxX;
								}
								
								if(y < 12){
									y = 12;
								}else if(y > maxY){
									y = maxY;
								}
        		        		$("#" + signatureContainerId + "_" + signatureDocObj.getId()).css({
        		        			"left": x + "px",
        		        			"top": y + "px",
        		        			"width": w + "px",
        		        			"height": h + "px"
        		        		});
            				}
            			}
            		}
            	}
            });
        }

        function signatureCallback(data){
        	var tmpList = JSON.parse(data);
        	for (var key in tmpList) {
        		var value = tmpList[key];
        		if (value) {
        			var signatureObj = new WebPDF.PDFData.PDFSignature();
        			signatureObj.setId(value.id);
        			signatureObj.setType(value.type);
        			signatureObj.setWidth(value.w);
        			signatureObj.setHeight(value.h);
        			if (value.type == WebPDF.PDFData.SignatureType.Text) {
        				signatureObj.setFontSize(value.fs);
        				signatureObj.setFontColor(value.fc);
        				signatureObj.setFontName(value.fn);
        				signatureObj.setSignatureText(value.txt);
        				signatureObj.setUnderLine(value.ul);
        				signatureObj.setItalic(value.i);
        				signatureObj.setBold(value.b);
        			} else {
                        var signaturePath = value.path;
                        signaturePath = signaturePath.replace(/^\//,"");
        				signatureObj.setFilePath(_readerApp.getOptions().url + signaturePath);
        			}
        			_signatureList[signatureObj.getId()] = signatureObj;
        			_curSignatureNum++;
        			if(_curSignatureNum >= _signatureListMax){
        				break;
        			}
        		}
        	}
        }
        //模块初始化;
        this.init = function () {
        	_signatureTool = new SignatureToolHandler(_readerApp, _self);
        	_readerApp.registerToolHandler(_signatureTool);
        	
        	_getSignatureList(signatureCallback);
        	
        	var signatureObj = new WebPDF.PDFData.PDFSignature();
    		signatureObj.setType(WebPDF.PDFData.SignatureType.Text);
    		signatureObj.setId(WebPDF.PDFData.BaseSignature.Text);
    		signatureObj.setSignatureText("");
    		signatureObj.setFontColor("#000000");
    		signatureObj.setFontName("Arial");
    		signatureObj.setFontSize(14);
    		signatureObj.setHeight(26);
    		signatureObj.setWidth(100);
        	_signatureList[WebPDF.PDFData.BaseSignature.Text] = signatureObj;
        	signatureObj = new WebPDF.PDFData.PDFSignature();
        	signatureObj.setType(WebPDF.PDFData.SignatureType.Text);
    		signatureObj.setId(WebPDF.PDFData.BaseSignature.Date);
    		signatureObj.setSignatureText("");
    		signatureObj.setFontColor("#000000");
    		signatureObj.setFontName("Arial");
    		signatureObj.setFontSize(14);
    		signatureObj.setHeight(26);
    		signatureObj.setWidth(100);
        	_signatureList[WebPDF.PDFData.BaseSignature.Date] = signatureObj;
        	
        	_bindEvents();
        	
        	var signatureMousePtHandler = new SignatureMousePtHandler(_self);
        	_readerApp.registerMousePtHandler(signatureMousePtHandler);
        	
        	_fouseEvent();
        };
        
        function _fouseEvent(){
        	jQuery(document).on("blur",".fwr-sign-input",function(){
        		_self.hideEditSign($(this).parent(),true);
		    }).on("focus",".fwr-sign-input",function(){
		    	var id = $(this).parent().attr("id");
		    	$("#"+id+"_fg").hide();
		    	$(this).parent().css("border","1px solid #f78f20");
		    	$(this).parent().find(".fwr-sign-dragImg").show();
		    	$(this).parent().find(".fwr-sign-delImg").show();
		    	$(this).parent().css("z-index",60);
		    	$(this).parent().find(".fwr-sign-scaleImg").show();
		    });
        };
        //模块卸载;
        this.unload = function () {
        };
        
        /**
         * Set the current signature
         * @param {String} singnatureId signature id
         */
        this.setCurSingnature = function(singnatureId, event) {
        	_curSignatureId = singnatureId;
        	_signatureTool.updateCursor(_curSignatureId);
        };
        /**
         * Get the current signature object
         * @returns {WebPDF.PDFData.PDFSignature | null} signature object
         */
        this.getCurSingnature = function() {
        	if (_curSignatureId) {
        		return _signatureList[_curSignatureId];
        	}
        	return null;
        };
        /**
         * set add signature to page complete event handler
         * @param {Function} eventhandler
         */
        this.setSignToPageCompleteEventHandler = function(eventhandler) {
        	if($.isFunction(eventhandler) || null){
        		_signToPageCompleteEventHandler = eventhandler;
            }
        };
        /**
         * Get the signature list.
         * @returns {Array.<String, WebPDF.PDFData.PDFSignature>} signature object list
         */
        this.getSingnatureList = function () {
        	var newlist = $.extend(true, {}, _signatureList);
        	newlist[WebPDF.PDFData.BaseSignature.Text] = undefined;
        	newlist[WebPDF.PDFData.BaseSignature.Date] = undefined;
        	return newlist;
        };
        /**
         * Get the current number of signatures
         * 
         * @returns {Number} the current number of signatures
         */
        this.getSingnatureCount = function () {
        	return _curSignatureNum;
        };
        /**
         * Get maximum number for signature
         * 
         * @returns {Number} maximum number
         */
        this.getSingnatureMaxLimit = function () {
        	return _signatureListMax;
        };
        
        /**
         * Add a signature
         * @param {WebPDF.PDFData.SignatureType} type Signature Type
         * @param {String} imgPath Image of base64 data
         * @param {Number} imgWidth The width of image
         * @param {Number} imgHeight The height of image
         * @example 
         * 		var signatureObj = signaturePlugin.addSingnature(
         * 			WebPDF.PDFData.SignatureType.Img,
         * 			".....ABJRU5ErkJggg==",
         * 			10,
         * 			10);
         * 
         * @param {String} text The contents of a text signature
         * @param {String} fontName The font name of a text signature
         * @param {Number} fontSize The font size of a text signature
         * @param {String} fontColor The font color of a text signature
         * @param {Boolean} bBold Whether in bold
         * @param {Boolean} bItalic Whether in italic
         * @param {Boolean} bUnderline Whether the underline
         * @example 
         * 		var signatureObj = signaturePlugin.addSingnature(
         * 			WebPDF.PDFData.SignatureType.Text,
         * 			null,null,null,
         * 			"signature text",
         * 			"Arial",
         * 			"16",
         * 			"#000000",
         * 			false,false,false);
         * 
         * @returns {WebPDF.PDFData.PDFSignature} new signature object
         */
        this.addSingnature = function (type,imgPath,imgWidth,imgHeight,text,fontName,fontSize,fontColor,bBold,bItalic,bUnderline) {
        	if(_signatureList.length > _signatureListMax){
        		return null;
        	}
        	if (type == WebPDF.PDFData.SignatureType.Img || type == WebPDF.PDFData.SignatureType.Text) {
        		var singnatureId = (new Date()).valueOf().toString();
        		var signatureObj = new WebPDF.PDFData.PDFSignature();
        		signatureObj.setType(type);
        		signatureObj.setId(singnatureId);
        		signatureObj.setHeight(imgHeight);
        		signatureObj.setWidth(imgWidth);
        		if (type == WebPDF.PDFData.SignatureType.Img) {
        			signatureObj.setFilePath(imgPath);
        		} else {
        			signatureObj.setSignatureText(text);
            		signatureObj.setFontName(fontName);
            		signatureObj.setFontSize(fontSize);
            		signatureObj.setFontColor(fontColor);
            		signatureObj.setBold(bBold);
            		signatureObj.setItalic(bItalic);
            		signatureObj.setUnderLine(bUnderline);
        		}
        		_signatureList[singnatureId] = signatureObj;
        		_signatureAddListId[singnatureId] = singnatureId;
        		_curSignatureNum++;
        		
        		_readerApp.setModified(null, null, true);
        		return signatureObj;
        	}
        };
        /**
         * Delete the signature
         * @param {String} singnatureId signature id.
         */
        this.deleteSingnature = function (singnatureId) {
        	if (!_signatureList[singnatureId]) {
        		return;
        	}
        	_signatureList[singnatureId] = undefined;
        	var flag = false;
        	if (_signatureAddListId[singnatureId]) {
        		_signatureAddListId[singnatureId] = undefined;
        		flag = true;
        	}
        	if(!flag){
				_signatureDeletedListId[singnatureId] = singnatureId;
			}
        	_curSignatureNum--;
        	
        	_readerApp.setModified(null, null, true);
        };
        
        /**
         * 获取保存的数据
         * @private
         */
        this.getSignatureSaveData = function(data){
        	var list = [];
        	for(var key in _signatureAddListId){
        		var value = _signatureAddListId[key];
        		if (value) {
        			list.push(_signatureList[value]);
        		}
        	}
        	if (list.length > 0) {
        		var sigdata = JSON.stringify(list);
				data.signatureData = sigdata.toString();
        	}
        	
        	var listDeleted = [];
        	for(var key in _signatureDeletedListId){
        		var value = _signatureDeletedListId[key];
        		if (value) {
        			listDeleted.push(value);
        		}
        	}
        	if (listDeleted.length > 0) {
        		var sigdeldata = JSON.stringify(listDeleted);
				data.signatureDelData = sigdeldata.toString();
        	}
        	
        	var listDoc = [];
        	var docView = _readerApp.getDocView();
        	var nPt2Pixel = _readerApp.getPixelsPerPoint();
        	var scale = docView.getScale();
        	for(var key in _signatureDocList){
        		var value = _signatureDocList[key];
        		if (value) {
        			var pageSignatureObj = {"index": value.index,"signatures":{}};
        			var pageView = docView.getPageView(value.index);
        			var bAdd = false;
        			for (var id in value.signatures) {
        				var signatureDocObj = value.signatures[id];
        				if (signatureDocObj) {
        					var addSignatureDocObj = new WebPDF.PDFData.PDFSignatureDoc();
        					var h = parseInt(signatureDocObj.getHeight() / nPt2Pixel + 0.5);
        					var bText = signatureDocObj.getType() == WebPDF.PDFData.SignatureType.Text;
        					if (bText) {
								if (!signatureDocObj.getSignatureText()) {
									continue;
								}
								addSignatureDocObj.setFontSize(parseInt(signatureDocObj.getFontSize() / nPt2Pixel + 0.5));
								addSignatureDocObj.setBold(signatureDocObj.getBold());
								addSignatureDocObj.setItalic(signatureDocObj.getItalic());
								addSignatureDocObj.setUnderLine(signatureDocObj.getUnderLine());
								addSignatureDocObj.setSignatureText(signatureDocObj.getSignatureText());
								addSignatureDocObj.setFontColor(signatureDocObj.getFontColor());
								addSignatureDocObj.setFontName(signatureDocObj.getFontName());
							} else {
								addSignatureDocObj.setFilePath(signatureDocObj.getFilePath());
								addSignatureDocObj.getSignatureJSONData()["scale"] = signatureDocObj.getHeight() / nPt2Pixel / signatureDocObj.getOriginalImgHeight();
							}
							var point = new WebPDF.PDFPoint(signatureDocObj.getPosX() * scale, signatureDocObj.getPosY() * scale);
							point = pageView.docPtToPDF(point);
							addSignatureDocObj.setPosX(parseInt(point.x + 0.5));
							var pointY = 0;
							if (bText) {
								pointY = parseInt(point.y - 15 + 0.5);
							} else {
								pointY = parseInt(point.y - h + 0.5);
							}
							addSignatureDocObj.setPosY(pointY);
							addSignatureDocObj.setType(signatureDocObj.getType());
							addSignatureDocObj.setId(signatureDocObj.getId());
							addSignatureDocObj.setSignatureId(signatureDocObj.getSignatureId());
							pageSignatureObj.signatures[addSignatureDocObj.getId()] = addSignatureDocObj;
							bAdd = true;
        				}
        			}
        			if (bAdd) {
        				listDoc.push(pageSignatureObj);
        			}
        		}
        	}
        	if (listDoc.length > 0) {
        		var sigdocdata = JSON.stringify(listDoc);
        		data.signatureDocData = sigdocdata.toString();
			}
        };
        
        /**
         * 判断是否在文档上进行了签名
         */
        this.checkSignatureInDoc = function(ignoreCheckTextContent){
        	for(var key in _signatureDocList){
        		var value = _signatureDocList[key];
        		if (value) {
        			for (var id in value.signatures) {
        				var signatureDocObj = value.signatures[id];
        				if (signatureDocObj) {
        					var bText = signatureDocObj.getType() == WebPDF.PDFData.SignatureType.Text;
        					if (!bText || ignoreCheckTextContent || signatureDocObj.getSignatureText()) {
        						return true;
							}
        				}
        			}
        		}
        	}
        	return false;
        }
        /**
         * 判断是否可以保存
         */
        this.canSave = function(){
        	for(var key in _signatureAddListId){
        		var value = _signatureAddListId[key];
        		if (value) {
        			return true;
        		}
        	}
        	for(var key in _signatureDeletedListId){
        		var value = _signatureDeletedListId[key];
        		if (value) {
        			return true;
        		}
        	}
            return _self.checkSignatureInDoc();
        };
        
        this.addSignatureToDocList = function(pageIndex, signatureDocObj) {
        	var pageSignatureObj = _signatureDocList[pageIndex];
        	if (!pageSignatureObj) {
        		pageSignatureObj = {"index": pageIndex,"signatures":{}};
        		_signatureDocList[pageIndex] = pageSignatureObj;
        	}
        	pageSignatureObj.signatures[signatureDocObj.getId()] = signatureDocObj;
        };
        
        this.deleteSignatureFromDocList = function(pageIndex, signatureDocObjId) {
        	var pageSignatureObj = _signatureDocList[pageIndex];
        	if (pageSignatureObj && pageSignatureObj.signatures[signatureDocObjId]) {
        		pageSignatureObj.signatures[signatureDocObjId] = undefined;
        	}
        };
        
        this.getSignatureFromDocList = function(pageIndex, signatureDocObjId) {
        	var pageSignatureObj = _signatureDocList[pageIndex];
        	if (pageSignatureObj) {
        		return pageSignatureObj.signatures[signatureDocObjId];
        	}
        	return null;
        };
        /**
         * 在页面上签名
         * @private
         */
        this.addSingnatureToPage = function (curPageView, singnatureObj, _oldPosX, _oldPosY, callback) {
        	/*var signatuerDocObj = _addSignatureToPage(curPageView, singnatureObj, _oldPosX, _oldPosY);
			callback(signatuerDocObj);
   		 	if (_signToPageCompleteEventHandler) _signToPageCompleteEventHandler();
   		 	return;
        	*/
        	var id = singnatureObj.getId();
			if (id == WebPDF.PDFData.BaseSignature.Date || 
					id == WebPDF.PDFData.BaseSignature.Text) {
				var signatuerDocObj = _addSignatureToPage(curPageView, singnatureObj, _oldPosX, _oldPosY);
				callback(signatuerDocObj);
       		 	if (_signToPageCompleteEventHandler) _signToPageCompleteEventHandler();
			} else if (_signcodeUrl) {
	       		 $.ajax({
	                    url: _signcodeUrl,
	                    dataType: 'json',
	                    success: function (response) {
	                   	 if(response && response.success == 1){
	                   		 	var signatuerDocObj = _addSignatureToPage(curPageView, singnatureObj, _oldPosX, _oldPosY, response.code);
	                   		 	callback(signatuerDocObj);
	                   		 	if (_signToPageCompleteEventHandler) _signToPageCompleteEventHandler();
	                        }else{
	                        	WebPDF.alert(_readerApp, null, "Failed to get the signature code.");
	                        	callback(null);
	                        	if (_signToPageCompleteEventHandler) _signToPageCompleteEventHandler();
	                        }
	                    },
	                    error: function () {
	                   	 WebPDF.alert(_readerApp, null, "Failed to get the signature code.");
	                   	 callback(null);
	                   	 if (_signToPageCompleteEventHandler) _signToPageCompleteEventHandler();
	                    }
	                });
	       	} else {
	       		WebPDF.alert(_readerApp, null, "Failed to get the signature code.");
	       		callback(null);
	       		if (_signToPageCompleteEventHandler) _signToPageCompleteEventHandler();
	       	}
        };
        
        function _createImgSignature(signatureDocObj, minWidth, minHeight, maxWidth, maxHeight, callback){                    
              var img = new Image();
              var filePath = signatureDocObj.getFilePath();
              if(filePath.indexOf('data') < 0){
            	  img.setAttribute('crossOrigin','anonymous');
              }
              img.src = filePath;
              var padding_left = 10;
              var padding_top = 20;
              var padding_bottom = 20;
              var img_minWidth =  minWidth;            
              var img_minHeight = minHeight;            
              var img_maxWidth  = maxWidth;          
              var img_maxHeight = maxHeight;  
               $(img).one('load', function() {       
                   
                  var canvass = document.createElement('canvas');            
                  var ctx = canvass.getContext('2d');  
                   
                   var img_width = img.width;
                   var img_height = img.height;
                   var left = 0;
                   var top = 0;
                   //如果最小框能放下，图片居中显示
                  if (img_minWidth >= img.width && img_minHeight >= img.height){
                      canvass.width = minWidth + padding_left;
                      canvass.height = minHeight + padding_top + padding_bottom;          
                      left = padding_left + (img_minWidth-img.width)/2;
                      top =  padding_top + (img_minHeight-img.height)/2;
                  }
                   //如果图片比最小框大
                  else if (img_minWidth < img.width && img_minHeight >= img.height){
                      if (img.width > img_maxWidth){
                          var scale = img_maxWidth/img.width;
                          img_width = img.width * scale;
                          img_height = img.height * scale;                          
                      }                     
                      canvass.width = img_width + padding_left;
                      canvass.height = minHeight + padding_top + padding_bottom;
                      left = padding_left;
                      top =  padding_top + (img_minHeight - img_height)/2;                           
                      
                  }
                   //如果图片比最小框高
                   else if (img_minWidth >= img.width && img.height > img_minHeight){
                      if (img.height > img_maxHeight){
                         var scale = img_maxHeight / img.height;
                         img_width = img.width * scale;
                         img_height = img.height * scale;  
                      }
                   
                      padding_top = padding_bottom = padding_top * Math.max(1,img_height /200);
                      canvass.width = minWidth + padding_left;
                      canvass.height = img_height + padding_top + padding_bottom;
                      left = padding_left + (img_minWidth - img_width)/2;
                      top =  padding_top;
                  }
                  else if (img.width > img_maxWidth || img.height > img_maxHeight){                      
                      var scale = Math.min( img_maxWidth / img.width, img_maxHeight/img.height);
                      img_width = img.width * scale;
                      img_height = img.height * scale;         
                      padding_left = padding_left * Math.max(1, img_width / 200);
                      padding_top = padding_bottom = padding_top * Math.max(1,img_height /200);
                      canvass.width = img_width + padding_left;
                      canvass.height = img_height + padding_top + padding_bottom;                     
                      top = padding_top;
                      left = padding_left;
                  }
                  else{
                      img_width = img.width;
                      img_height = img.height;                
                      padding_left = padding_left * Math.max(1,img_width / 200);
                      padding_top = padding_bottom = padding_top * Math.max(1 ,img_height /200);
                      canvass.width = img_width + padding_left;
                      canvass.height = img_height + padding_top + padding_bottom;                     
                      top = padding_top;
                      left = padding_left;
                }                    
                      
                 
                ctx.drawImage(img, left, top, img_width, img_height);
                       
                  var width  = canvass.width;
                  var height = canvass.height;    
                  ctx.strokeStyle = "#006CD4";
                  ctx.lineWidth = 2 * height/200;
               
                  ctx.beginPath();
                  ctx.moveTo(30, padding_top/2);
                  ctx.lineTo(padding_left*1.5, padding_top/2);             
                  ctx.quadraticCurveTo(2, padding_top/2, 2, padding_top*1.5);
                  ctx.lineTo(2, height - padding_bottom*1.5);
                  ctx.quadraticCurveTo(2,height-padding_bottom/2,padding_left*1.5,height-padding_bottom/2);
                  ctx.lineTo(30, height-padding_bottom/2);              
                  ctx.stroke();            

                  var fontsize = 20;//Math.max(15,parseInt(15 * height/200));
                  ctx.font="bold " + fontsize +"px proxima nova-light";   
                  ctx.fillStyle = "#5f6062";
                  ctx.fillText("Signed by",30, padding_top/2 + fontsize/4);
                  ctx.fillText(signatureDocObj.getId(), 30, height - padding_bottom/2 + fontsize/4);
                  canvass.toDataURL("image/png");
                  var dataUrl = canvass.toDataURL("image/png");
                  signatureDocObj.setFilePath(dataUrl);
                  signatureDocObj.setOriginalImgWidth(canvass.width);
                  signatureDocObj.setOriginalImgHeight(canvass.height);
                //  imgEle.attr("src", dataUrl);
                   callback();
               }).each(function() {                 
            	   if(this.complete) $(this).load();
               });     
        };
        function _addSignatureToPage(curPageView, singnatureObj, _oldPosX, _oldPosY, signDocId) {
        	var scale = _readerApp.getDocView().getScale();
        	var pageViewWidth = curPageView.getPageViewWidth();
			var pageViewHeight = curPageView.getPageViewHeight();
        	var singnatureIdToPage = signDocId ? signDocId : (new Date()).valueOf().toString();
        	var signatureContainerId = _self.getSignatureContainerId(curPageView);
        	var signatureObjId = signatureContainerId + '_' + singnatureIdToPage;
        	var signatureDocObj = new WebPDF.PDFData.PDFSignatureDoc();
        	signatureDocObj.setId(singnatureIdToPage);
        	signatureDocObj.setType(singnatureObj.getType());
        	signatureDocObj.setSignatureId(singnatureObj.getId());
        	var signDiv = $("<div class='fwr-signature' style='background-color:transparent;border: 1px solid #f78f20;'></div>");            
            signDiv.attr("signatureType", singnatureObj.getType());
            signDiv.attr("id", signatureObjId);
            
        	if (singnatureObj.getType() == WebPDF.PDFData.SignatureType.Text) {
        		var defaultText = "";
        		var w = parseInt(singnatureObj.getWidth() * scale + 0.5),
    			h = parseInt(singnatureObj.getHeight() * scale + 0.5);
        		if (singnatureObj.getId() == WebPDF.PDFData.BaseSignature.Date) {
        			defaultText = new Date().toLocaleDateString();
        		} else if (singnatureObj.getSignatureText()) {
        			defaultText = singnatureObj.getSignatureText();
        		}
        		if (defaultText) {
        			w = Math.max(w, parseInt(GetCurrentStrWidth(defaultText,singnatureObj.getFontSize()) * scale + 0.5));
        		}
    			var maxX = pageViewWidth-w-23;
    			var maxY = pageViewHeight-h-12;
    			_oldPosX = parseInt(_oldPosX - w / 2 + 0.5);
    			_oldPosY = parseInt(_oldPosY - h / 2 + 0.5);
    			if(_oldPosX < 2){
    				_oldPosX = 2;
    			} else if(_oldPosX > maxX){
    				_oldPosX = maxX;
    			}
    			
    			if(_oldPosY < 12){
    				_oldPosY = 12;
    			}else if(_oldPosY > maxY){
    				_oldPosY = maxY;
    			}
        		signDiv.css({padding:"2px 2px 2px 2px", left: _oldPosX+'px',top: _oldPosY+'px', width:w+'px', height:h+'px'});
        		signDiv.html('<textarea id="' + signatureObjId + '_input" class="fwr-sign-input' + (defaultText?'':' fwr-sign-input-placeholder') +
    			'" style="font-size:' + singnatureObj.getFontSize() + 'px;color:' + singnatureObj.getFontColor() +';font-family:' + 
    			singnatureObj.getFontName() + ';">' + defaultText + '</textarea>');
    			
        		signatureDocObj.setFontColor(singnatureObj.getFontColor());
        		signatureDocObj.setFontName(singnatureObj.getFontName());
        		signatureDocObj.setFontSize(singnatureObj.getFontSize());
        		signatureDocObj.setBold(singnatureObj.getBold());
        		signatureDocObj.setItalic(singnatureObj.getItalic());
        		signatureDocObj.setUnderLine(singnatureObj.getUnderLine());
        		signatureDocObj.setHeight(singnatureObj.getHeight());
        		signatureDocObj.setSignatureText(defaultText);
        		signatureDocObj.setWidth(w / scale);
        	} 
            else {                 
                var minOriginalImgWidth = 160, minOriginalImgHeight = 66;
                signatureDocObj.setFilePath(singnatureObj.getFilePath());
                _createImgSignature(signatureDocObj, minOriginalImgWidth, minOriginalImgHeight, 500, 500, function(){                      
                    
                    //先计算原始高宽            	
				    var originalImgWidth = signatureDocObj.getOriginalImgWidth();
                    var originalImgHeight = signatureDocObj.getOriginalImgHeight();


                    var minWidth = 16;
                    var minHeight = 16;
                    var standardWidth = 180, standardHeight = 60;
                    var w = originalImgWidth, h = originalImgHeight;
                    var wscale = w / standardWidth,
                        hscale = h / standardHeight;
                    if ((wscale > hscale) && (w > standardWidth)) {
                        w = standardWidth;
                        h = parseInt(h / wscale + 0.5);
                    } else if (h > standardHeight){
                        w = parseInt(w / hscale + 0.5);
                        h = standardHeight;
                    }
                    if (w < minWidth) {
                        w = minWidth;
                        h = w * originalImgHeight / originalImgWidth;
                    }
                    if (h < minHeight) {
                        h = minHeight;
                        w = h * originalImgWidth / originalImgHeight;
                    }
                    var objWidth = w, objHeight = h;
                    w = parseInt(w * scale + 0.5);
                    h = parseInt(h * scale + 0.5);
                    var maxX = pageViewWidth-w-23;
                    var maxY = pageViewHeight-h-12;
                    _oldPosX = parseInt(_oldPosX - w / 2 + 0.5);
                    _oldPosY = parseInt(_oldPosY - h / 2 + 0.5);
                    if(_oldPosX < 2){
                        _oldPosX = 2;
                    } else if(_oldPosX > maxX){
                        _oldPosX = maxX;
                    }

                    if(_oldPosY < 12){
                        _oldPosY = 12;
                    }else if(_oldPosY > maxY){
                        _oldPosY = maxY;
                    }				

                    signDiv.css({padding:0, left: _oldPosX+'px',top: _oldPosY+'px', width:w+'px', height:h+'px', cursor:"move"});		
                    var img = $('<img class="fwr-sign-img" style="left:0;top:0;"></img>');
                    img.attr("src", signatureDocObj.getFilePath());
                    signatureDocObj.setHeight(objHeight);
                    signatureDocObj.setWidth(objWidth);
                    signDiv.append(img);                
                });
            
			
			}
			signDiv.append('<div class="fwr-sign-delImg"></div>');
			signDiv.append('<div direction="sw" style="left:-3.5px;bottom:-3.5px;cursor:sw-resize" class="fwr-sign-scaleImg"></div>');
			signDiv.append('<div direction = "nw" style="left:-3.5px;top:-3.5px;cursor:nw-resize" class="fwr-sign-scaleImg"></div>');
			signDiv.append('<div direction = "se" style="right:-3.5px;bottom:-3.5px;cursor:se-resize" class="fwr-sign-scaleImg"></div>');
			signDiv.append('<div id="' + signatureObjId +'_fg" class="fwr-sign-fg"/>');						
			var posX = parseInt(_oldPosX / scale + 0.5),
				posY = parseInt(_oldPosY / scale + 0.5);
			signatureDocObj.setPosX(posX);
			signatureDocObj.setPosY(posY);
			_self.addSignatureToDocList(curPageView.getPageIndex(), signatureDocObj);
			$("#" + signatureContainerId).append(signDiv);
			_readerApp.setModified(null, null, true);
			return signatureDocObj;
        }
        
        /**
         * 从页面中删除签名
         * @private
         */
        this.deleteSingnatureFromPage = function (signatureDocObjId, _curPageView) {
        	if (_curPageView) {
        		var pageIndex = _curPageView.getPageIndex();
        		_selft.deleteSignatureFromDocList(pageIndex, signatureDocObjId);
        	} else {
        		for (var pageIndex in _signatureDocList) {
        			_self.deleteSignatureFromDocList(pageIndex, signatureDocObjId);
        		}
        	}
        };
        
        /**
         * 从页面中修改签名
         * @private
         */
        this.getSingnatureFromPage = function (signatureDocObjId, _curPageView) {
        	var singnatureDocObj = null;
        	if (_curPageView) {
        		var pageIndex = _curPageView.getPageIndex();
        		singnatureDocObj = _self.getSignatureFromDocList(pageIndex, signatureDocObjId);
        	} else {
        		for (var pageIndex in _signatureDocList) {
        			singnatureDocObj = _self.getSignatureFromDocList(pageIndex, signatureDocObjId);
        			if (singnatureDocObj) {
        				break;
        			}
        		}
        	}
        	return singnatureDocObj;
        };
        
        /**
         * 获取某页面签名容器id
         * @private
         */
        this.getSignatureContainerId = function(pageView) {
        	var signatureContainerId = pageView.getPageViewContainerID() + "_signatureContainer";
        	var obj = $("#" + signatureContainerId);
        	if (!obj || obj.length <=0) {
        		var html = "<div id='" + signatureContainerId + "'/>";
        		$("#" + pageView.getPageViewContainerID()).append(html);
        	}
        	return signatureContainerId;
        };
        
        this.getSignatureDocObjIdFromObj = function(obj) {
    		var itemId = obj.attr("id");
    		if (itemId) {
    			var index = itemId.lastIndexOf('_');
    			return itemId.substring(index+1);
    		}
    		return "";
    	};
    	
    	this.getPageViewInfo = function(visiblePageRange,docView,pageX,pageY){
    		 for (var i = visiblePageRange.begin; i <= visiblePageRange.end; i++) {
                 var tmpPageView = docView.getPageView(i);
                 var pageOffsetHtmlDoc = $("#" + tmpPageView.getPageViewContainerID()).offset();
                 var pageViewWidth = tmpPageView.getPageViewWidth();
                 var pageViewHeight = tmpPageView.getPageViewHeight();
                 pageViewRect = new WebPDF.PDFRect(pageOffsetHtmlDoc.left, pageOffsetHtmlDoc.top,
                         pageOffsetHtmlDoc.left + pageViewWidth, pageOffsetHtmlDoc.top + pageViewHeight);
                 WebPDF.RectUtils.normalize(pageViewRect);
                 if (WebPDF.RectUtils.ptInRect(pageViewRect, pageX, pageY)) {
                	 var pageViewInfos = {};
                	 pageViewInfos.pageViewRect = pageViewRect;
                	 pageViewInfos.pageView = tmpPageView;
                     return pageViewInfos;
                 }
             }
    	};
    };

    exports.createPlugin = function (readerApp) {
    	return new WebPDF.SignaturePlugin(readerApp);
    };
});